<template>
  <div class="container">
    <TableWrapper :title="'菜单管理'">
      <template #header>
        <el-form ref="form" :model="query" label-width="120px" :inline="true">
          <el-form-item label="部门名称：">
            <el-input
              style="width: 260px"
              v-model="query.deptName"
              placeholder="请输入部门名称"
            ></el-input>
          </el-form-item>
          <el-form-item label="部门状态：">
            <el-select
              v-model="query.status"
              style="width: 220px"
              placeholder="请选择部门状态"
            >
              <el-option
                v-for="dict in dict.type.sys_normal_disable"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item class="ml15">
            <el-button
              icon="el-icon-search"
              type="primary"
              @click="searchChange"
              >搜索</el-button
            >
            <el-button icon="el-icon-refresh-left" @click="searchReset"
              >重置</el-button
            >
          </el-form-item>
        </el-form>
      </template>

      <template #main>
        <div style="margin-bottom: 18px">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            @click="beforeOpen('add')"
            v-hasPermission="['system:dept:add']"
            >新增</el-button
          >
          <el-button
            type="info"
            plain
            icon="el-icon-sort"
            @click="toggleExpandAll"
            >展开 / 折叠</el-button
          >
        </div>
        <el-table
          v-if="refreshTable"
          :data="data"
          :header-cell-style="headStyle"
          row-key="deptId"
          :default-expand-all="isExpandAll"
          :tree-props="{ children: 'children' }"
        >
          <el-table-column align="center" prop="deptName" label="部门名称">
          </el-table-column>
          <el-table-column align="center" prop="deptType" label="部门类型">
            <template slot-scope="scope">
              <dict-tag
                :options="dict.type.sys_dept_type"
                :value="scope.row.deptType"
              />
            </template>
          </el-table-column>
          <el-table-column align="center" prop="leader" label="负责人">
          </el-table-column>
          <el-table-column align="center" prop="phone" label="联系电话">
          </el-table-column>
          <el-table-column align="center" prop="userCount" label="人员数">
          </el-table-column>
          <el-table-column align="center" prop="status" label="部门状态">
            <template slot-scope="scope">
              <dict-tag
                :options="dict.type.sys_normal_disable"
                :value="scope.row.status"
              />
            </template>
          </el-table-column>
          <el-table-column align="center" prop="remark" label="描述">
            <template slot-scope="scope">
              <span>{{
                scope.row.remark ? scope.row.remark : "暂无相关描述"
              }}</span>
            </template>
          </el-table-column>
          <el-table-column align="center" label="操作">
            <template slot-scope="scope">
              <el-button
                type="text"
                icon="el-icon-plus"
                @click="beforeOpen('add', scope.row)"
                v-hasPermission="['system:dept:add']"
                >新增子部门</el-button
              >
              <el-button
                type="text"
                icon="el-icon-edit"
                @click="beforeOpen('edit', scope.row)"
                v-hasPermission="['system:dept:edit']"
                >编辑</el-button
              >
              <el-button
                v-if="scope.row.ancestors != 0"
                @click="handelDel(scope.row)"
                type="text"
                icon="el-icon-delete"
                v-hasPermission="['system:dept:delete']"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </template>
    </TableWrapper>

    <!-- 修改框 -->
    <el-dialog
      :title="(ntype == 'add' ? '添加' : '修改') + '部门'"
      :visible.sync="dialogVisible"
      width="680px"
      append-to-body
    >
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col>
            <el-form-item label="上级部门：" prop="parentId">
              <Treeselect
                v-model="form.parentId"
                placeholder="请选择部门"
                :options="deptOptions"
                :show-count="true"
              ></Treeselect>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="部门名称：" prop="deptName">
              <el-input
                v-model="form.deptName"
                placeholder="请输入部门名称"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="显示排序：" prop="orderNum">
              <el-input-number
                style="width: 100%"
                v-model="form.orderNum"
                controls-position="right"
                :min="0"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="负责人：" prop="leader">
              <el-input
                v-model="form.leader"
                placeholder="请输入部门负责人"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系电话：" prop="phone">
              <el-input
                v-model="form.phone"
                placeholder="请输入联系电话"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="邮箱：" prop="email">
              <el-input
                v-model="form.email"
                placeholder="请输入联系邮箱"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态：">
              <el-radio-group v-model="form.status">
                <el-radio
                  v-for="item in dict.type.sys_normal_disable"
                  :key="item.raw.dictCode"
                  :label="item.value"
                  >{{ item.label }}</el-radio
                >
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleSave()" :loading="loading"
          >保 存</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
import TableWrapper from "@/components/Table/TableWrapper.vue";
import {
  getList,
  getDeptTree,
  getNotice,
  update,
  add,
  remove,
} from "@/api/system/dept.js";

export default {
  components: { TableWrapper },
  dicts: ["sys_normal_disable", "sys_dept_type"],
  data() {
    return {
      // 搜索数据
      query: {},
      // 表数据
      data: [],
      // 弹出框数据
      form: {},
      // 控制弹出框
      dialogVisible: false,
      // 操作类型
      ntype: "add",
      // 部门树
      deptOptions: [],
      // 按钮
      loading: false,
      // 校验结果
      validate: false,
      // 重新渲染表格状态
      refreshTable: true,
      // 是否展开，默认全部折叠
      isExpandAll: true,
      // 表单校验
      rules: {
        parentId: [
          { required: true, message: "上级部门不能为空", trigger: "blur" },
        ],
        deptName: [
          { required: true, message: "部门名称不能为空", trigger: "blur" },
        ],
        orderNum: [
          { required: true, message: "显示排序不能为空", trigger: "blur" },
        ],
        email: [
          {
            type: "email",
            message: "请输入正确的邮箱地址",
            trigger: ["blur", "change"],
          },
        ],
        phone: [
          {
            pattern: /^0?(13|14|15|16|17|18|19)[0-9]{9}$/,
            message: "请输入正确的手机号码",
            trigger: "blur",
          },
        ],
      },
    };
  },
  created() {
    // 重置表单
    this.resetForm();
    // 获取数据
    this.refreshChange();
    // 获取部门树
    getDeptTree().then((res) => {
      this.deptOptions = res.data;
      // 默认选中第一个
      this.form.deptId = res.data[0].id;
    });
  },
  methods: {
    // 搜索重置
    searchReset() {
      this.query = {};
      this.refreshChange();
    },
    // 搜索点击
    searchChange() {
      this.refreshChange();
    },
    // 刷新数据
    refreshChange() {
      this.onLoad(this.query);
    },
    // 重置表单
    resetForm() {
      this.form = {
        parentId: undefined,
        deptName: undefined,
        orderNum: 0,
        leader: undefined,
        phone: undefined,
        email: undefined,
        status: "0",
      };
    },
    // 展开/折叠操作
    toggleExpandAll() {
      this.refreshTable = false;
      this.isExpandAll = !this.isExpandAll;
      this.$nextTick(() => {
        this.refreshTable = true;
      });
    },
    // 处理表单开启
    beforeOpen(ntype, row) {
      this.ntype = ntype;
      // 重置标签
      this.resetForm();

      // 如果是编辑
      if (["edit", "view"].includes(ntype)) {
        // 查询详情
        getNotice(row.deptId).then((res) => {
          this.form = res.data;
        });
      }

      if (["add"].includes(ntype)) {
        this.form.parentId = row.deptId;
      }
      // 修改按钮状态
      this.loading = false;
      // 打开提交框
      this.dialogVisible = true;
    },
    // 添加数据
    handleSave() {
      // 校验表单
      this.validateForm();
      if (!this.validate) {
        return;
      }
      if (this.ntype == "add") {
        this.sendAjax(add, this.form);
      } else {
        this.sendAjax(update, this.form);
      }
    },
    // 校验表单
    validateForm() {
      this.$refs.formRef.validate((valid) => {
        if (valid) {
          this.validate = true;
          return true;
        } else {
          this.validate = false;
          return false;
        }
      });
    },
    // 发送 ajax 请求
    sendAjax(Interface, row) {
      // 调用接口发送请求
      Interface(row).then(
        (res) => {
          if (res.code == 200) {
            this.$modal.msgSuccess(res.msg);
            // 关闭弹窗
            this.dialogVisible = false;
            // 刷新列表
            this.refreshChange();
          } else {
            this.$modal.msgError(res.msg);
          }
          this.loading = false;
        },
        () => {
          this.$modal.msgError("系统错误，请稍后尝试！");
        }
      );
    },
    // 删除数据
    handelDel(row) {
      this.$modal
        .confirm("确定将选择数据删除?")
        .then(() => {
          return remove(row.deptId);
        })
        .then(() => {
          this.refreshChange();
          this.$modal.msgSuccess("操作成功!");
        });
    },
    // 重载数据
    onLoad(params = {}) {
      let values = {
        ...params,
        // 排序字段
        orderByColumn: "order_num, create_time",
        // 排序方式 desc 降序 asc 升序
        isAsc: "asc",
      };

      this.loading = true;
      getList(Object.assign(values, this.query)).then((res) => {
        this.data = res.data;
        this.loading = false;
      });
    },
    /** 转换菜单数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.menuId,
        label: node.menuName,
        children: node.children,
      };
    },
    // 自定义表头颜色
    headStyle({ row, rowIndex }) {
      if (rowIndex === 0) {
        return {
          backgroundColor: "#F8FAFF",
          fontWeight: 800,
          color: "#515a6e",
        };
      }
    },
  },
};
</script>
